package code.class1;

import cn.hutool.core.util.ArrayUtil;

/**
 *
 * 反转字符串3,
 * 题目：每隔 k 个数字反转字符串
 */
public class Code13_ReverseStr3 {

    public static void main(String[] args) {
        String str = "abcdefghi"; // abc def ghi  => cba fed ihg
        int k = 2;
        String ans = reverseStr(str, k);
        System.out.println(ArrayUtil.toString(ans));
    }

    public static String reverseStr(String message, int k) {
        char[] chars = message.toCharArray();
        int start = 0, end = k - 1;
        while (end < chars.length) {
            reverse(chars, start, end);
            start = end + 1;
            end = end + k;
        }

        return new String(chars);
    }

    public static void reverse(char[] chars, int p1, int p2) {
        while (p1 < p2) {
            swap(chars, p1++, p2--);
        }
    }

    public static void swap(char[] arr, int x, int y) {
        char t = arr[x];
        arr[x] = arr[y];
        arr[y] = t;
    }
}
